package com.atguigu.zkb.service.impl;


import com.atguigu.zkb.constant.CacheAbleConstant;
import com.atguigu.zkb.service.CacheOpsService;
import com.atguigu.zkb.utils.Jsons;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

//@Service
public class CacheOpsServiceImpl implements CacheOpsService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public <T> T getDataFromCache(String cacheKey, Class<T> tClass) {
        String jsonStrFromCache = stringRedisTemplate.opsForValue().get(cacheKey);
        if (!StringUtils.hasText(jsonStrFromCache)) {
            return null;
        }
        return Jsons.jsonToObj(jsonStrFromCache,tClass);
    }

    @Override
    public <T> T getDataFromCache(String cacheKey, TypeReference<T> tTypeReference) {
        String jsonStrFromCache = stringRedisTemplate.opsForValue().get(cacheKey);
        if (!StringUtils.hasText(jsonStrFromCache)) {
            return null;
        }
        return Jsons.jsonToObj(jsonStrFromCache,tTypeReference);
    }

    @Override
    public void saveDataToCache(String cacheKey, Object object) {
        String serializableStr  = Jsons.objToStr(object);
        long ttl = CacheAbleConstant.SYNC_HAS_DATA_TTL;
        for (String appAllRegex : Jsons.getAppAllRegex()) {
            if (regexRule(appAllRegex,serializableStr)){
                ttl = CacheAbleConstant.SYNC_HAS_NO_DATA_TTL;
            }
        }
        stringRedisTemplate.opsForValue().set(cacheKey,serializableStr,ttl, TimeUnit.SECONDS);
    }
    public boolean regexRule(String rule, String compareContent) {
        return Pattern.matches(rule, compareContent);
    }
}
